#include "srdetailedauditinfo.h"

#include <thread>

#include <QTextCodec>
#include <QProcess>
#include <QTimer>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <QCheckBox>
#include <QLineEdit>
#include <QLabel>
#include <QJsonDocument>
#include <QTableView>
#include <QHeaderView>
#include <QStandardItemModel>
#include <QFileDialog>
#include <QJsonObject>
#include <QJsonValue>
#include <QJsonArray>
#include <QMessageBox>
#include <QDebug>

#include <OEMessageBox>
#include <OENotifyMessageBox>


/// private xls lib
#include <oeexcelreader.h>
#include <oeexcelwriter.h>

#include <auditcryptogram.h>

#include "srdatabase.h"


#define TABLE_IDX       (0)
#define TABLE_AUDIT_ID  (1)
#define TABLE_STATUS    (2)
#define TABLE_SUM       (3)
#define TABLE_TXID      (4)
#define TABLE_CRT_TIME  (5)
#define TABLE_COUNT     (6)




SRDetailedAuditInfo::SRDetailedAuditInfo(QWidget *parent) : QWidget(parent),
    bThreadReadExcel_(false)
{
    QVBoxLayout * layout = new QVBoxLayout();
    QHBoxLayout * layout_navigation = new QHBoxLayout();
    QHBoxLayout * layout_query = new QHBoxLayout();
    QHBoxLayout * layout_operator = new QHBoxLayout();


    QPushButton* btn_export = new QPushButton(tr("导出"));
    btnAllSelect_  = new QPushButton("全  选");
    QLabel* lab_audit_num = new QLabel(tr("审核编号:"));
    edtAuditNum_ = new QLineEdit();
    QRegExp regQuote("[0-9a-zA-Z]{1,36}");
    QRegExpValidator* quote_validator = new QRegExpValidator(regQuote, this);
    edtAuditNum_->setValidator(quote_validator);
    QPushButton* btn_query = new QPushButton(tr("查询"));
    btn_query->setObjectName("auditQuery");

    tableView_ = new QTableView();
    model_ = new QStandardItemModel();
    tableView_->setModel(model_);

    QHeaderView *headerGoods = tableView_->horizontalHeader();
    //SortIndicator为水平标题栏文字旁边的三角指示器
    headerGoods->setSortIndicator(0, Qt::AscendingOrder);
    headerGoods->setSortIndicatorShown(true);
    connect(headerGoods, SIGNAL(sectionClicked(int)),
            tableView_, SLOT (sortByColumn(int)));
    connect(btnAllSelect_, &QPushButton::clicked,
            this, [=] {
        if (model_->rowCount() == 0) {
            return;
        }
        if (btnAllSelect_->text() == "全  选") {
            for (int i = 0; i < model_->rowCount(); ++i)
                model_->item(i)->setCheckState(Qt::CheckState::Checked);
            btnAllSelect_->setText("取消全选");
        }
        else {
            for (int i = 0; i < model_->rowCount(); ++i)
                model_->item(i)->setCheckState(Qt::CheckState::Unchecked);
            btnAllSelect_->setText("全  选");
        }

    });

    // model 初始化
    model_->setColumnCount(6);
    model_->setHeaderData(TABLE_IDX, Qt::Horizontal, tr("审核编号"));
    model_->setHeaderData(TABLE_AUDIT_ID, Qt::Horizontal, tr("转出地址"));
    model_->setHeaderData(TABLE_STATUS, Qt::Horizontal, tr("转入地址"));
    model_->setHeaderData(TABLE_CRT_TIME, Qt::Horizontal, tr("审批时间"));
    model_->setHeaderData(TABLE_SUM, Qt::Horizontal, tr("地址金额"));
    model_->setHeaderData(TABLE_TXID, Qt::Horizontal, tr("手续费"));

    // tableview 初始化
    tableView_->setSelectionBehavior(QAbstractItemView::SelectRows); // 选中整行
    tableView_->setSelectionMode(QAbstractItemView::SelectionMode::SingleSelection); // 只能单选
    tableView_->setEditTriggers(QTableView::EditTrigger::NoEditTriggers);
    tableView_->setAlternatingRowColors(true);
    tableView_->setMouseTracking(true);

    tableView_->setColumnWidth(0, 80);
    tableView_->setColumnWidth(2, 80);
    tableView_->setColumnWidth(3, 80);
    tableView_->horizontalHeader()->setSectionResizeMode(0,QHeaderView::Interactive);
    tableView_->horizontalHeader()->setSectionResizeMode(1,QHeaderView::Stretch);
    tableView_->horizontalHeader()->setSectionResizeMode(4,QHeaderView::Stretch);
    tableView_->horizontalHeader()->setSectionResizeMode(5,QHeaderView::Stretch);

#ifdef QT_DEBUG
    for(int i = 0; i < 10; ++i) {
        QStandardItem *item = new QStandardItem();
        item->setCheckable(true);
        item->setText(QString::number(i));
        item->setCheckState(Qt::Unchecked);
        model_->setItem(i, 0, item);
        model_->setItem(i, 1, new QStandardItem("654654654"));
        model_->setItem(i, 2, new QStandardItem("admin"));
        model_->setItem(i, 3, new QStandardItem("admin"));
        model_->setItem(i, 4, new QStandardItem("admin"));
        model_->setItem(i, 5, new QStandardItem("admin"));
    }
#else
#endif

    // 信号链接
    connect(btn_query, &QPushButton::clicked,
            this, &SRDetailedAuditInfo::onQuery);

    // 大小
    btn_export->setFixedSize(64,24);
    btnAllSelect_->setFixedSize(87,24);
    edtAuditNum_->setFixedSize(87,24);
    btn_query->setFixedSize(58,24);


    // 布局
    layout_query->addWidget(lab_audit_num,0,Qt::AlignLeft);
    layout_query->addWidget(edtAuditNum_,0,Qt::AlignLeft);
    layout_query->addWidget(btn_query,0,Qt::AlignLeft);

    layout_operator->addWidget(btnAllSelect_,0,Qt::AlignRight);
    layout_operator->addWidget(btn_export,0,Qt::AlignRight);

    layout_navigation->addLayout(layout_query);
    layout_navigation->addStretch();
    layout_navigation->addLayout(layout_operator);
    layout->addLayout(layout_navigation);
    layout->addWidget(tableView_);

    setLayout(layout);
}

void SRDetailedAuditInfo::setAuditId(const QString &_auditId)
{
    auditId_ = _auditId;
}

void SRDetailedAuditInfo::setAuditData(const QString &_data)
{
    auditData_ = _data;
}


void SRDetailedAuditInfo::showEvent(QShowEvent *event)
{
    if (auditData_.isEmpty()) {
        // 如果为空，则读取试图自己读取文件
    }


    int transaction_count = 0;
    QString txid = "";
    // decode item.signData;
    QJsonParseError jsonError;
    QJsonDocument doucment = QJsonDocument::fromJson(auditData_.toUtf8(), &jsonError);
    if (!doucment.isNull() && (jsonError.error == QJsonParseError::NoError)) {
        if (doucment.isObject()) {
            QJsonObject object = doucment.object();

            if (object.contains("txid")) {
                txid = object.value("txid").toString();
            }


            if (object.contains("vout")) {
                QJsonArray vout_arr = object.value("vout").toArray();
                if (!vout_arr.isEmpty())
                    transaction_count = vout_arr.size();
            }
        }
    }

    //

}


void SRDetailedAuditInfo::onQuery() {
    // @remakr : pan
    QString choose_txt = edtAuditNum_->text().trimmed();

    if (!choose_txt.isEmpty()) {
        QList<QStandardItem*> temp_list = model_->findItems(
                   choose_txt, Qt::MatchContains, TABLE_AUDIT_ID);

        QList<QStandardItem*>::iterator item = temp_list.begin();
        for (;item != temp_list.end(); ++item) {
            int old = tableView_->currentIndex().row();
            if ((*item)->row() > old) {
                tableView_->selectRow((*item)->row());
                break;
            }
        }
        if (item == temp_list.end()) {
            tableView_->selectRow(temp_list.at(0)->row());
        }
    }

}

void SRDetailedAuditInfo::insertModelData(const QString &id,
                                          const QString &audit_id,
                                          const int &is_export,
                                          const QString &transaction_count,
                                          const QString &txid,
                                          const QString &crt_time)
{

    QStandardItem *item = new QStandardItem();
    item->setCheckable(true);
    item->setText(id);
    item->setCheckState(Qt::Unchecked);

    int idx = model_->rowCount();

    model_->setItem(idx, TABLE_IDX, item);
    model_->setItem(idx, TABLE_AUDIT_ID, new QStandardItem(audit_id));
    if (is_export == 0) {
        model_->setItem(idx, TABLE_STATUS, new QStandardItem(tr("未导出")));
    }
    else {
        model_->setItem(idx, TABLE_STATUS, new QStandardItem(tr("已导出")));
    }

    model_->setItem(idx, TABLE_SUM, new QStandardItem(transaction_count));
    model_->setItem(idx, TABLE_TXID, new QStandardItem(txid));
    model_->setItem(idx, TABLE_CRT_TIME, new QStandardItem(crt_time));

    for (int i = 0; i < TABLE_COUNT; ++i)
        model_->item(idx,i)->setTextAlignment(Qt::AlignCenter);
}
